import React, { createContext, useContext, useState } from 'react';
import { Button, Form, Input, Table } from 'antd';
import { RECORDTYPE, COLTYPE } from './typeing';
import styles from './index.module.less'
const moveInput = () => {
    const EditableContext = createContext<any>(null);
    const [form] = Form.useForm();
    const dataSource:RECORDTYPE[] = [
        {
            key: '0',
            name: '小赵',
            age: '18',
            address: 'London'
        },
        {
            key: '1',
            name: '小张',
            age: '18',
            address: 'London',
        },
        {
            key: '2',
            name: '小王',
            age: '18',
            address: 'London',
        },
    ];
    const EditableRow = ({ ...props }) => {
        return (
            <Form form={form} component={false}>
                <EditableContext.Provider value={form}>
                    <tr {...props} />
                </EditableContext.Provider>
            </Form>
        );
    };
    const EditableCell = ({ children, dataIndex, record }: { children: undefined | JSX.Element, dataIndex: number, record: RECORDTYPE[] }) => {
        const [editing, setEditing] = useState(false);
        const form = useContext<any>(EditableContext);
        if (children) {
            children = editing ? (
                <Form.Item name={dataIndex}>
                    <Input />
                </Form.Item>
            ) : (
                <div onClick={() => (setEditing(!editing), form.setFieldsValue({ [dataIndex]: record[dataIndex] }))}>
                    {children}
                </div>
            );
        }
        return <td>{children}</td>;
    };
    const defaultColumns = [
        {
            title: 'name',
            dataIndex: 'name',
            width: 100
        },
        {
            title: 'age',
            dataIndex: 'age',
            width: 100
        },
        {
            title: 'address',
            dataIndex: 'address',
            width: 100
        },
    ];
    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };
    const columns = defaultColumns.map((col: COLTYPE) => {
        const { dataIndex, title } = col;
        return {
            ...col,
            onCell: (record: RECORDTYPE) => {
                return {
                    record,
                    dataIndex,
                    title,
                }
            },

        };
    });

    const handleSave = () => {
        console.log(form.getFieldsValue());
    }
    return (
        <div className={styles.editingTable}>
            <Button onClick={handleSave}>{'保存'}</Button>
            <Table
                components={components}
                bordered
                dataSource={dataSource}
                columns={columns}
                pagination={false}
            />
        </div>

    );
};
export default moveInput;